package com.ssd.http.process;

import com.ssd.exception.LogicException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常拦截器
 * 用于统一处理全局异常，返回统一的错误响应
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理LogicException异常
     *
     * @param e LogicException异常对象
     * @return 包含错误信息的响应实体
     */
    @ResponseBody
    @ExceptionHandler(value = LogicException.class)
    public ResponseEntity<String> exceptionHandler(LogicException e){
        log.error("controller call error",e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }

    /**
     * 处理DuplicateKeyException异常
     * 当数据库中存在重复键时触发
     *
     * @param e DuplicateKeyException异常对象
     * @return 包含错误信息的响应实体
     */
    @ResponseBody
    @ExceptionHandler(value = DuplicateKeyException.class)
    public ResponseEntity<String> exceptionHandler(DuplicateKeyException e){
        log.error("controller call error",e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("已存在此名称的对象");
    }

    /**
     * 处理所有未被捕获的异常
     *
     * @param e Exception异常对象
     * @return 包含错误信息的响应实体
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> exceptionHandler(Exception e){
        log.error("error",e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
}

